/**
 *
 */
package com.longrise.android.byjk.plugins.course.pay;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.app.BYJKAppLike;
import com.longrise.android.byjk.utils.TimeHelper;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.MessageConstants;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.ReceiverType;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.android.byjk.utils.ListenUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.PayItemView;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;

import java.math.BigDecimal;
import java.util.Calendar;


/**
 * simple introduction
 * <p/>
 * <p/>
 * detailed comment
 *
 * @author callxkj 2016-1-5
 * @see
 * @since 1.0
 */
public class PaymentActivity extends BaseActivity implements OnClickListener, OnPayItemListener {

    private static final String TAG = "PaymentActivity";

    private ImageView mImage_Icon;

    private ImageView mImage_Falg;

    private TextView mText_TitleTextView;

    private TextView mText_TeachTextView;

    private RelativeLayout mRlwxpay;

    private IWXAPI mWxapi;

//    private EntityBean mBean;

    private String mCourseid;

    private String mScoreIdString; // 我的课程id支付时候使用

    private RelativeLayout mRlalipay;

    private static final int SDK_PAY_FLAG = 1;

    private static final int SHOW_WAIT_DIALOG = 3;

    private static final int ALIAPY_SUCCESS = 4;

    private static final int WXPAY_SUCCESS = 5;

    private static int PAY_STATUS = ALIAPY_SUCCESS; //支付宝支付成功

    private int mOnError = 0;       //调用失败次数   最高3次
    private int mSleepTime = 3000; //延时调用时间

    private boolean mIsPayFail = false;

    private boolean isFirstUnselectyue = true;//是否是第一次取消选择余额

    private int mMoneyStatus = MONEY_NONE;//保宝余额里面有多少钱
    private static final int MONEY_NONE = 0;
    private static final int MONEY_LESS = 1;
    private static final int MONEY_ENOUGH = 2;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    PrintLog.d(TAG, "resultInfo:" + resultInfo);

                    String resultStatus = payResult.getResultStatus();
                    PrintLog.d(TAG, "resultStatus:" + resultStatus);

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        new Thread() {
                            public void run() {
                                Message msg = mHandler.obtainMessage();
                                msg.what = SHOW_WAIT_DIALOG;
                                mHandler.sendMessage(msg);
                                try {
                                    Thread.sleep(mSleepTime);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                } finally {
                                    Message msg2 = mHandler.obtainMessage();
                                    msg2.what = ALIAPY_SUCCESS;
                                    mHandler.sendMessage(msg2);
                                }
                            }

                        }.start();

                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误

                        }

                        View mDialogview = View.inflate(mContext, R.layout.dialog_courses_evaluate, null);
                        TextView mTvtitle = (TextView) mDialogview.findViewById(R.id.dialog_courses_title);
                        mTvtitle.setText("支付宝支付");
                        ImageView mIv = (ImageView) mDialogview.findViewById(R.id.dialog_share_success_iv);
                        mIv.setImageResource(R.drawable.icon_tips);
                        TextView mTvcontent = (TextView) mDialogview.findViewById(R.id.dialog_courses_content);
                        mTvcontent.setText("支付失败");
                        TextView mTvbt = (TextView) mDialogview.findViewById(R.id.dialog_courses_evaluate_bt);
                        mTvbt.setOnClickListener(PaymentActivity.this);
                        DialogUtil.getInstance().creatAlertDialog(mContext, mDialogview, 266, 195);

                    }
                    break;
                }

                case SHOW_WAIT_DIALOG: {
                    DZZWTools.showNotBackWaitDialog(mContext);
                    break;
                }

                case ALIAPY_SUCCESS:
                    PAY_STATUS = ALIAPY_SUCCESS;
                    saveSuccessResult();
                    toConfirmAlipayresult();
                    Tracker_Google.getInstance().addEvent("Pay-course", "Success-paid", "支付成功");
                    break;

                case WXPAY_SUCCESS:
                    PAY_STATUS = WXPAY_SUCCESS;
                    saveSuccessResult();
                    toConfirmwxresult();
                    Tracker_Google.getInstance().addEvent("Pay-course", "Success-paid", "支付成功");
                    break;
                default:
                    break;
            }
        }

    };

    private String mName;

    private Double mRealprice;

    private String out_trade_no;

    private LinearLayout mLlzf;

    private LinearLayout mLlksxx;

    private Button mBtksxx;

    private long mTime;
    private RelativeLayout mRl1;
    private View mDivide;
    private RelativeLayout mRldetail;
    private RelativeLayout mRlfail;
    private WXpaySuccessBroadCast mBroadcast;
    private TextView mTvfail;
    private PayItemView mPvyezf;
    private PayItemView mPvwxzf;
    private PayItemView mPvalizf;
    private TextView mTvtips;
    private EntityBean mSignupBean;
    private double mYEmoney;
    private YEpaySuccessBroadCast mYeBroadcast;
    public static final String COURSE_BEAN = "course_bean";
    public static final String SIGNUP_BEAN = "signup_bean";
    private GoogleApiClient client;
    private Toolbar mToolbar;
    private TextView mTvname;
    private TextView mTvzjhm;
    private ScrollView mSv;
    private RelativeLayout mRLbtm;
    private Button mBtPay;
    private TextView mTvcourseTime;

    @Override
    public int getContentViewId(@Nullable Bundle state) {
        if (state != null) {
            onRestoreState(state);
        } else {
            getExtraData();
        }
        return R.layout.lfview_payment;
    }

    @Override
    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle("支付页面");
        setSupportActionBar(mToolbar);
        mImage_Icon = (ImageView) findViewById(R.id.ifview_payment_iv);
        mImage_Falg = (ImageView) findViewById(R.id.ifview_payment_iv_success);
        mText_TitleTextView = (TextView) findViewById(R.id.ifview_payment_tv1);
        mText_TeachTextView = (TextView) findViewById(R.id.ifview_payment_tv2);
        mTvcourseTime = (TextView) findViewById(R.id.ifview_payment_tv3);
        // 微信支付
        //mRlwxpay = (RelativeLayout) mRootView.findViewById(R.id.ifview_payment_rl_wx);
        // 支付宝
        // mRlalipay = (RelativeLayout) mRootView.findViewById(R.id.ifview_payment_rl_alipay);

        // 支付方式
        mLlzf = (LinearLayout) findViewById(R.id.ifview_payment_ll1);
        // 开始学习
        mLlksxx = (LinearLayout) findViewById(R.id.ifview_payment_ll2);
        // 开始学习的按钮
        mBtksxx = (Button) findViewById(R.id.ifview_payment_bt);
        // 支付宝支付成功 但是请求服务器失败了的显示
        mRl1 = (RelativeLayout) findViewById(R.id.ifview_payment_rl1);
        // mDivide = mRootView.findViewById(R.id.lfview_payment_devide);
        mRldetail = (RelativeLayout) findViewById(R.id.lfview_payment_Rldetail);
        mRlfail = (RelativeLayout) findViewById(R.id.lfview_payment_rlfail);
        //支付失败提示
        mTvfail = (TextView) findViewById(R.id.ifview_payment_tvfail);
        //余额支付
        mPvyezf = (PayItemView) findViewById(R.id.ifview_payment_111111);
        //微信支付
        mPvwxzf = (PayItemView) findViewById(R.id.ifview_payment_wx);
        //支付宝支付
        mPvalizf = (PayItemView) findViewById(R.id.ifview_payment_zfb);
        //底部的LinearLayout
        mRLbtm = (RelativeLayout) findViewById(R.id.ifview_payment_rl);
        //确认支付按钮
        mBtPay = (Button) findViewById(R.id.ifview_payment_buy_bt);
        //提示
        mTvtips = (TextView) findViewById(R.id.ifview_payment_tips);
        //姓名
        mTvname = (TextView) findViewById(R.id.bb_pay_name);
        //证件号码
        mTvzjhm = (TextView) findViewById(R.id.bb_pay_zjhm);
        //scrollview
        mSv = (ScrollView) findViewById(R.id.ifview_payment_scrollv);

        Tracker_Google.getInstance().addGoogleScreenName("课程支付");
        mWxapi = BYJKAppLike.mIWXAPI;
        Calendar calendar = Calendar.getInstance();
        mTime = calendar.getTime().getTime();
        initData();
        regEvent(true);
        clientRequest();
    }

    /**
     * sjz调整
     */
    private void getExtraData() {
        Intent extraIntent = getIntent();
        mCourseid = extraIntent.getStringExtra(COURSE_BEAN);
        String signupBeanString = extraIntent.getStringExtra(SIGNUP_BEAN);
        mSignupBean = (EntityBean) JSONSerializer.getInstance().DeSerialize(signupBeanString, EntityBean.class);
    }

    /**
     * sjz调整
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(COURSE_BEAN, mCourseid);
        String value = JSONSerializer.getInstance().Serialize(mSignupBean);
        outState.putString(SIGNUP_BEAN, value);
    }

    /**
     * sjz调整
     */
    private void onRestoreState(Bundle state) {
        if (state != null) {
            mCourseid = state.getString(COURSE_BEAN);
            String value = state.getString(SIGNUP_BEAN);
            mSignupBean = (EntityBean) JSONSerializer.getInstance().DeSerialize(value, EntityBean.class);
        }
    }

    public void initData() {
//        Intent intent = getIntent();
//        String beanString = intent.getStringExtra(COURSE_BEAN);
//        String signupBeanString = intent.getStringExtra(SIGNUP_BEAN);
//        mBean = (EntityBean) JSONSerializer.getInstance().DeSerialize(beanString, EntityBean.class);
//        mSignupBean = (EntityBean) JSONSerializer.getInstance().DeSerialize(signupBeanString, EntityBean.class);


        mPvyezf.setImage(R.drawable.bb_logo);
        mPvyezf.setName(mContext.getString(R.string.yezf));
        mPvwxzf.setImage(R.drawable.by_ic_pay_we);
        mPvwxzf.setName(mContext.getString(R.string.wxzf));
        mPvalizf.setImage(R.drawable.by_ic_pay_ali);
        mPvalizf.setName(mContext.getString(R.string.zfbzf));

        String personname = UserInfor.getInstance().getPersonname();
        mTvname.setText(TextUtils.isEmpty(personname) ? "无" : personname);
        mTvzjhm.setText(UserInfor.getInstance().getUsersfzh());

        String errText = mContext.getString(R.string.paynotice);
        String[] split = errText.split("！");
        if (split.length > 1) {
            String s2 = split[1];
            String s3 = "<font color = #ff9900 ><B>您已支付成功！</B></font>";
            String s4 = s3 + s2;
            mTvfail.setText(Html.fromHtml(s4));
        }

        mIsPayFail = false;
    }

    public void regEvent(boolean b) {
        mToolbar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (mRlwxpay != null) {
            mRlwxpay.setOnClickListener(b ? this : null);
        }
        if (mRlalipay != null) {
            mRlalipay.setOnClickListener(b ? this : null);
        }
        if (mBtksxx != null) {
            mBtksxx.setOnClickListener(b ? this : null);
        }
        if (mBtPay != null) {
            mBtPay.setOnClickListener(b ? this : null);
        }
        if (mPvwxzf != null) {
            mPvwxzf.setOnPayItemListener(b ? this : null);
        }
        if (mPvalizf != null) {
            mPvalizf.setOnPayItemListener(b ? this : null);
        }
        if (mPvyezf != null) {
            mPvyezf.setOnPayItemListener(b ? this : null);
        }

    }

    /**
     * 数据库查询支付宝是否支付成功
     */
    private void toConfirmAlipayresult() {
        EntityBean bean = new EntityBean();
        bean.set("out_trade_no", out_trade_no);
        PrintLog.d(TAG, "out_trade_no_阿里回调:" + out_trade_no);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl,
                "bbt_pay_getAliPayResult", fbean, new LoadDataManager.OnRequestCallListener() {

            private boolean alicsuccess = false;

            @Override
            public void onSuccess(String key, String service, Object result) {
                alicsuccess = true;
                parseResult(result);
            }

            @Override
            public void onFinished(String key, String service) {
                if (!alicsuccess) {
                    DZZWTools.dismissNotBackDialog();
                }

            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

            }
        });

    }


    /**
     * 数据库查询微信是否支付成功
     */
    private void toConfirmwxresult() {
        EntityBean bean = new EntityBean();
        bean.set("out_trade_no", out_trade_no);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl,
                "bbt_pay_getWechatPayResult", fbean, new LoadDataManager.OnRequestCallListener() {
            private boolean wxcsuccess = false;

            @Override
            public void onSuccess(String key, String service, Object result) {
                wxcsuccess = true;
                parseResult(result);
            }

            @Override
            public void onFinished(String key, String service) {
                if (!wxcsuccess) {
                    DZZWTools.dismissNotBackDialog();
                }

            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {


            }
        });
    }

    /**
     * 处理微信 支付宝 调用服务区查询是否支付成功的结果
     */
    private void parseResult(Object result) {
        try {
            EntityBean bean = (EntityBean) result;
            PrintLog.d(TAG, "bean3:" + bean);
            Integer resultstate = bean.getInt("resultstate");
            if (resultstate == 0) { // 0 支付失败
                if (mOnError < 3) {
                    sleep();
                } else {
                    DZZWTools.dismissNotBackDialog();
                    mOnError = 0;
                    //三次都失败
                    mSv.setVisibility(View.GONE);
//                    mRl1.setVisibility(View.GONE);
                    // mDivide.setVisibility(View.GONE);
//                    mRldetail.setVisibility(View.GONE);
                    mRlfail.setVisibility(View.VISIBLE);
                    mRLbtm.setVisibility(View.GONE); //底部支付的rl
                    mIsPayFail = true;
                    mToolbar.setTitle("支付完成");
                    Tracker_Google.getInstance().addGoogleScreenName("支付完成延时");
                    Tracker_Google.getInstance().addEvent("Pay-course", "Faild-open", "已支付，开通失败");
                }

            } else if (resultstate == 1) { // 1 支付成功
                mLlksxx.setVisibility(View.VISIBLE);
                mLlzf.setVisibility(View.INVISIBLE);
                mRLbtm.setVisibility(View.GONE); //底部支付的rl
                mImage_Falg.setVisibility(View.VISIBLE);
                Intent intent = new Intent(MessageConstants.PAY_SUCCESS);
                intent.putExtra(ReceiverType.RECEIVER_KEY, ReceiverType.PAY_SUCESS);
                mContext.sendBroadcast(intent);
                mOnError = 0;
                mToolbar.setTitle("支付完成");
                DZZWTools.dismissNotBackDialog();
                Tracker_Google.getInstance().addGoogleScreenName("支付完成");

            }

        } catch (Exception e) {
            DZZWTools.dismissNotBackDialog();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.ifview_payment_bt:// 开始学习
                finish();
                ListenUtil.getInstance().setPay(1);
                break;

            case R.id.dialog_courses_evaluate_bt: //支付宝支付失败后
                DialogUtil.getInstance().dismiss();
                break;
            case R.id.ifview_payment_buy_bt: //确认支付按钮
                toConfirmPay();
            default:
                break;
        }

    }

    /**
     * 获取保宝支付余额
     */
    private void getbbAccount() {
        //bbt_fee_sAccountBalance
        EntityBean bean = new EntityBean();
        bean.set("userid", UserInfor.getInstance().getUserid());
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, "bbt_fee_sAccountBalance", fbean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                parseAccountResult(result);
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished(String key, String service) {

            }
        });


    }

    /**
     * 保宝余额
     */
    private void parseAccountResult(Object result) {
        try {
            mRLbtm.setVisibility(View.VISIBLE);
            mLlzf.setVisibility(View.VISIBLE);
            EntityBean bean = (EntityBean) result;
            String result1 = bean.getString("result");
            if (TextUtils.isEmpty(result1)) { //账户没钱xxccccc
                noMoney();
            } else {
                //result有可能为空或者为double
                Double result2 = bean.getDouble("result");
                if (result2 == 0) { //账户没钱
                    noMoney();
                } else if (mRealprice > result2) { //余额小于课程的价钱
                    lessMoney(result2);
                } else {  //余额大于或者等于课程的价钱
                    mYEmoney = mRealprice;
                    enoughMoney(result2);
                }
            }

        } catch (Exception e) {

        }

    }

    /**
     * 保宝余额账户没钱
     * <p/>
     * 余额支付不可选；
     * 用户可以在微信支付、支付宝支付中二选一；
     */
    private void noMoney() {
        mMoneyStatus = MONEY_NONE;
        mPvyezf.setUnChecked();
        mPvyezf.setRightText("可用余额0.00元");
        isFirstUnselectyue = false;
        mPvwxzf.setChecked(true);
    }

    /**
     * 余额小于课程的价钱
     */
    private void lessMoney(double money) {
        mMoneyStatus = MONEY_LESS;
        mPvyezf.setChecked(true);
        BigDecimal bd = new BigDecimal(money);
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        mPvyezf.setRightText("可用余额" + bd + "元");
        mTvtips.setText("注：建议您使用余额+微信或支付宝合并支付");
    }

    /**
     * 余额大于课程的价钱
     */
    private void enoughMoney(double money) {
        mMoneyStatus = MONEY_ENOUGH;
        mPvyezf.setChecked(true);
        BigDecimal bd = new BigDecimal(money);
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        mPvyezf.setRightText("可用余额" + bd + "元");
        mTvtips.setText("注：建议您使用余额支付");

    }


    private void clientRequest() {
        DZZWTools.showWaitDialog(mContext);
        EntityBean bean = new EntityBean();
        bean.set("pendingid", mCourseid);
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        EntityBean serBean = new EntityBean();
        serBean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_fee_sPendingPayCourseBean", serBean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                DZZWTools.dismissDialog(null);
                EntityBean bean = (EntityBean) result;
                if (bean.getString("resultstate").equals("1")) {
                    EntityBean resultBean = bean.getBean("result");
                    setData(resultBean);
                    getbbAccount();//先请求到课程的价钱 然后请求余额
                } else {
                    DZZWTools.showToast(mContext, bean.getString("resultdesc"), 1000 * 2);
                }
            }

            @Override
            public void onFinished(String key, String service) {
                DZZWTools.dismissDialog(null);
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(mContext, mContext.getString(R.string.networkerror), 1000 * 2);
                finish();
            }
        });
    }

    /**
     * 设置数据
     */
    private void setData(EntityBean bean) {
        try {
            if (bean != null) {
                mBtPay.setText("确认支付");
                mRLbtm.setVisibility(View.VISIBLE);
                // 该课程id
                mScoreIdString = bean.get("courseid").toString();
                String realpic = bean.getString("realpic");
                if (realpic != null) {
                    Glide.with(mContext).load(realpic).into(new GlideDrawableImageViewTarget(mImage_Icon) {
                        @Override
                        public void onLoadFailed(Exception e, Drawable errorDrawable) {
                            super.onLoadFailed(e, errorDrawable);
                            mImage_Icon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.img03));
                        }
                    });
                }
                mRealprice = bean.getDouble("price");
                mBtPay.setText("支付 ￥" + mRealprice);
                mName = bean.get("name").toString();
                mText_TitleTextView.setText(mName);
                String grouptime = bean.get("grouptime").toString();
                String resulttime = TimeHelper.formateTime(grouptime);
                String time = "课程时长: " + resulttime ;
                mTvcourseTime.setText(time);


                String teacher = bean.getString("teachername", "");
                mText_TeachTextView.setText("讲师: " + teacher);

                if (mRealprice > 0) {
                    mLlzf.setVisibility(View.VISIBLE);
                    mLlksxx.setVisibility(View.INVISIBLE);
                    //mBtconfirm.setVisibility(View.VISIBLE);//余额加载出来了再显示按钮
                    mImage_Falg.setVisibility(View.INVISIBLE);
                } else
                // 价格为0 直接开始学习
                {
                    mLlksxx.setVisibility(View.VISIBLE);
                    mLlzf.setVisibility(View.INVISIBLE);
                    mRLbtm.setVisibility(View.GONE);
                    mImage_Falg.setVisibility(View.VISIBLE);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付宝
     */
    private void toAlipay() {
        String userid = UserInfor.getInstance().getUserid();
        String userName = UserInfor.getInstance().getPersonname();
        boolean checked = mPvyezf.isChecked();
        double yue = 0;
        if (checked) {
            yue = 1.00;
        }
        String os_type = "ANDROID";
        EntityBean bean = new EntityBean();
        bean.set("trainsignup", mSignupBean);
        bean.set("userid", userid);
        bean.set("username", userName);
        bean.set("yue", yue);
        bean.set("os_type", os_type);
        bean.set("IOS_edition", 1);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        DZZWTools.showWaitDialog(mContext);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_pay_getAlipayPayUrl2", fbean, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean bean = (EntityBean) result;
                    PrintLog.d(TAG, "bean2:" + bean.toString());
                    int resultstate = (Integer) bean.get("resultstate");
                    String resultdesc = bean.getString("resultdesc");
                    if (resultstate == 200) {
                        EntityBean msresult = bean.getBean("result");
                        out_trade_no = msresult.getString("out_trade_no");
                        final String payInfo = msresult.getString("url");

                        Runnable payRunnable = new Runnable() {

                            @Override
                            public void run() {
                                // 构造PayTask 对象
                                PayTask alipay = new PayTask((Activity) mContext);
                                // 调用支付接口，获取支付结果
                                String result = alipay.pay(payInfo, true);

                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };

                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    } else {
                        if ("您已购买该培训计划".equals(resultdesc)) {
                            Intent intent = new Intent(MessageConstants.PAY_SUCCESS);
                            intent.putExtra(ReceiverType.RECEIVER_KEY, ReceiverType.PAY_SUCESS);
                            mContext.sendBroadcast(intent);
                            mToolbar.setTitle("支付完成");
                            DZZWTools.showToast(mContext, resultdesc, 0);
                        } else {
                            View mDialogview = View.inflate(mContext, R.layout.dialog_courses_evaluate, null);
                            TextView mTvtitle = (TextView) mDialogview.findViewById(R.id.dialog_courses_title);
                            mTvtitle.setText("支付宝支付");
                            ImageView mIv = (ImageView) mDialogview.findViewById(R.id.dialog_share_success_iv);
                            mIv.setImageResource(R.drawable.icon_tips);
                            TextView mTvcontent = (TextView) mDialogview.findViewById(R.id.dialog_courses_content);
                            mTvcontent.setText("支付失败");
                            TextView mTvbt = (TextView) mDialogview.findViewById(R.id.dialog_courses_evaluate_bt);
                            mTvbt.setOnClickListener(PaymentActivity.this);
                            DialogUtil.getInstance().creatAlertDialog(mContext, mDialogview, 266, 195);
                        }
                    }
                } catch (Exception e) {
                    DZZWTools.showToast(mContext, "支付失败", 0);
                }
            }

            @Override
            public void onFinished(String key, String service) {
                DZZWTools.dismissDialog(null);
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(mContext, "支付失败", 0);
            }
        });

    }

    /**
     * 微信支付
     */
    private void toWxpay() {
        String userid = UserInfor.getInstance().getUserid(); // 用户id
        String userName = UserInfor.getInstance().getPersonname();
        boolean checked = mPvyezf.isChecked();
        double yue = 0;
        if (checked) {
            yue = 1.00;
        }
        EntityBean bean = new EntityBean();
        String os_type = "ANDROID";
        bean.set("trainsignup", mSignupBean);
        bean.set("userid", userid);
        bean.set("username", userName);
        bean.set("yue", yue);
        bean.set("os_type", os_type);
        bean.set("IOS_edition", 1);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        DZZWTools.showWaitDialog(mContext); // http://192.168.3.231:8080/BBT/restservices/bbapp/
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_pay_WChatPay2", fbean, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    DZZWTools.dismissDialog(null);
                    EntityBean bean = (EntityBean) result;
                    PrintLog.d(TAG, "bean:" + bean.toString());
                    int resultstate = (Integer) bean.get("resultstate");
                    String resultdesc = bean.getString("resultdesc");
                    if (resultstate == 200) {
                        EntityBean resultbean = bean.getBean("result");
                        out_trade_no = resultbean.getString("out_trade_no");
                        PayReq req = new PayReq();
                        req.appId = (String) resultbean.get("appid");
                        req.nonceStr = (String) resultbean.get("noncestr");
                        req.packageValue = (String) resultbean.get("package");
                        req.partnerId = (String) resultbean.get("partnerid");
                        req.prepayId = (String) resultbean.get("prepayid");
                        req.sign = (String) resultbean.get("sign");
                        req.timeStamp = String.valueOf(resultbean.getLong("timestamp"));

                        boolean wxAppInstalled = mWxapi.isWXAppInstalled();
                        PrintLog.d(TAG, "wxAppInstalled:" + wxAppInstalled);
                        if (wxAppInstalled) {
                            boolean sendReq = mWxapi.sendReq(req);
                            PrintLog.d(TAG, "sendReq:" + sendReq);
                            registerBroadcast();
                        } else {
                            DZZWTools.showToast(mContext, mContext.getResources().getString(R.string.wx_not_installed), 0);
                        }
                    } else {
                        if ("您已购买该培训计划".equals(resultdesc)) {
                            Intent intent = new Intent(MessageConstants.PAY_SUCCESS);
                            intent.putExtra(ReceiverType.RECEIVER_KEY, ReceiverType.PAY_SUCESS);
                            mContext.sendBroadcast(intent);
                            mToolbar.setTitle("支付完成");
                            DZZWTools.showToast(mContext, resultdesc, 0);
                        } else {
                            View mDialogview = View.inflate(mContext, R.layout.dialog_courses_evaluate, null);
                            TextView mTvtitle = (TextView) mDialogview.findViewById(R.id.dialog_courses_title);
                            mTvtitle.setText("微信支付");
                            ImageView mIv = (ImageView) mDialogview.findViewById(R.id.dialog_share_success_iv);
                            mIv.setImageResource(R.drawable.icon_tips);
                            TextView mTvcontent = (TextView) mDialogview.findViewById(R.id.dialog_courses_content);
                            mTvcontent.setText("支付失败");
                            TextView mTvbt = (TextView) mDialogview.findViewById(R.id.dialog_courses_evaluate_bt);
                            mTvbt.setOnClickListener(PaymentActivity.this);
                            DialogUtil.getInstance().creatAlertDialog(mContext, mDialogview, 266, 195);
                        }
                    }
                } catch (Exception e) {
                    DZZWTools.showToast(mContext, "支付失败", 0);
                }
            }

            @Override
            public void onFinished(String key, String service) {
                DZZWTools.dismissDialog(null);

            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(mContext, "支付失败", 0);
            }
        });

    }

    /**
     * 纯粹余额支付
     */
    private void toYEpay() {
        String userid = UserInfor.getInstance().getUserid(); // 用户id
        String userName = UserInfor.getInstance().getPersonname();
        EntityBean bean = new EntityBean();
        bean.set("trainsignup", mSignupBean);
        bean.set("userid", userid);
        bean.set("username", userName);
        bean.set("os_type", "ANDROID");
        bean.set("IOS_edition", 1);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        DZZWTools.showWaitDialog(mContext);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, "bbt_pay_yuEPay", fbean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean bean = (EntityBean) result;
                    int resultstate = bean.getInt("resultstate");
                    EntityBean resultbean = bean.getBean("result");
                    if (resultstate == 1) {
                        out_trade_no = resultbean.getString("out_trade_no", "");
                        if (TextUtils.isEmpty(out_trade_no)) { //如果没有这个单号 则是老的接口
                            Integer snum = resultbean.getInteger("snum", 0);
                            if (snum == 1) { //支付成功
                                showYEsuccessDialog();
                                payYEsuccess();
                            } else {
                                showYEfail();
                            }
                        } else { //有单号则是新接口
                            showYEsuccessDialog();
                            saveSuccessResult();
                            toConfirmAlipayresult(); //余额支付  阿里支付 微信支付 我们公司后台的消息队列走的是同一个方法
                        }
                    } else {
                        showYEfail();
                    }
                } catch (Exception e) {
                    showYEfail();
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(mContext, "支付失败", 0);
            }

            @Override
            public void onFinished(String key, String service) {
                DZZWTools.dismissDialog(null);
            }
        });
    }


    /**
     * 余额支付成功的弹窗
     */
    private void payYEsuccess() {
        mLlksxx.setVisibility(View.VISIBLE);
        mLlzf.setVisibility(View.INVISIBLE);
        mRLbtm.setVisibility(View.GONE);
        mImage_Falg.setVisibility(View.VISIBLE);
        Intent intent = new Intent(MessageConstants.PAY_SUCCESS);
        intent.putExtra(ReceiverType.RECEIVER_KEY, ReceiverType.PAY_SUCESS);
        mContext.sendBroadcast(intent);
        mOnError = 0;
        mToolbar.setTitle("支付完成");
    }

    /**
     * 显示余额支付成功弹窗
     */
    private void showYEsuccessDialog() {
        View mDialogview = View.inflate(mContext, R.layout.dialog_courses_evaluate, null);
        TextView mTvtitle = (TextView) mDialogview.findViewById(R.id.dialog_courses_title);
        mTvtitle.setText("余额支付");
        ImageView mIv = (ImageView) mDialogview.findViewById(R.id.dialog_share_success_iv);
        TextView mTvcontent = (TextView) mDialogview.findViewById(R.id.dialog_courses_content);
        TextView mTvbt = (TextView) mDialogview.findViewById(R.id.dialog_courses_evaluate_bt);
        mTvcontent.setText("支付成功");
        mTvbt.setOnClickListener(this);
        DialogUtil.getInstance().creatAlertDialog(mContext, mDialogview, 266, 195);
    }


    /**
     * 余额支付失败的弹窗
     */
    private void showYEfail() {
        View mDialogview = View.inflate(mContext, R.layout.dialog_courses_evaluate, null);
        TextView mTvtitle = (TextView) mDialogview.findViewById(R.id.dialog_courses_title);
        mTvtitle.setText("余额支付");
        ImageView mIv = (ImageView) mDialogview.findViewById(R.id.dialog_share_success_iv);
        mIv.setImageResource(R.drawable.icon_tips);
        TextView mTvcontent = (TextView) mDialogview.findViewById(R.id.dialog_courses_content);
        mTvcontent.setText("支付失败");
        TextView mTvbt = (TextView) mDialogview.findViewById(R.id.dialog_courses_evaluate_bt);
        mTvbt.setOnClickListener(PaymentActivity.this);
        DialogUtil.getInstance().creatAlertDialog(mContext, mDialogview, 266, 195);
    }


    /**
     * 确认支付
     */
    private void toConfirmPay() {
        if (mPvwxzf.isChecked()) { //微信支付
            if (accessible()) {
                toWxpay();
                Tracker_Google.getInstance().addEvent("Pay-course", "Wechat-pay", "微信支付");
            }
        } else if (mPvalizf.isChecked()) {
            if (accessible()) {
                toAlipay();
                Tracker_Google.getInstance().addEvent("Pay-course", "Alipay ", "支付宝支付");
            }
        } else if (mMoneyStatus == MONEY_ENOUGH && mPvyezf.isChecked()) {
            if (accessible()) {
                registerYEBroadcast();
                Intent intent = new Intent(mContext, InputPasswordActivity.class);
                intent.putExtra("money", mYEmoney);
                mContext.startActivity(intent);
            }
        } else if (mMoneyStatus == MONEY_LESS && mPvyezf.isChecked()) { //余额不足的时候需要合并支付或者单独用支付宝微信支付
            DZZWTools.showToast(mContext, "您当前余额不足", 1);
        } else {
            DZZWTools.showToast(mContext, "请选择支付方式", 1);
        }

    }

    private void registerYEBroadcast() {
        if (mYeBroadcast == null) {
            mYeBroadcast = new YEpaySuccessBroadCast();
            IntentFilter filter = new IntentFilter();
            filter.addAction(MessageConstants.YEPAY_SUCCESS);
            mContext.registerReceiver(mYeBroadcast, filter);
        }
    }

    /**
     * 注册广播
     */
    private void registerBroadcast() {
        if (mBroadcast == null) {
            mBroadcast = new WXpaySuccessBroadCast();
            IntentFilter filter = new IntentFilter();
            filter.addAction(MessageConstants.WXPAY_SUCCESS);
            mContext.registerReceiver(mBroadcast, filter);
        }
    }

    /**
     * 取消广播注册
     */
    private void unRegisterBroadcast() {
        if (mBroadcast != null) {
            mContext.unregisterReceiver(mBroadcast);
            mBroadcast = null;
        }
        if (mYeBroadcast != null) {
            mContext.unregisterReceiver(mYeBroadcast);
            mYeBroadcast = null;
        }
    }

//    /**
//     * @see ILSMsgListener#onLSMsg(int, Object[])
//     */
//    @Override
//    public Object onLSMsg(int type, Object... objects) {
//
//        int value = ListenUtil.getInstance().getPay();
//        if (MessageConstants.ONRESUME == type && MessageConstants.ONRESUMEO.equals(objects[0])) {
//            if (value == 2 && UserInfor.getInstance().isToConfirm_wx()) { //微信支付成功后的回调
//            }
//            ListenUtil.getInstance().setPay(0);
//        }
//        return null;
//    }

    @Override
    public void onCheck(View view, Boolean checked) {
        switch (view.getId()) {
            case R.id.ifview_payment_111111: //余额支付
                if (isFirstUnselectyue) {
                    if (mMoneyStatus == MONEY_ENOUGH) {
                        mPvyezf.setChecked(true);
                        showConfrimDialog(true, 1);
                    } else if (mMoneyStatus == MONEY_LESS) {
                        mPvyezf.setChecked(true);
                        showConfrimDialog(false, 1);
                    }
                } else {
                    if (mMoneyStatus == MONEY_LESS) {

                    } else {
                        mPvalizf.setChecked(false);
                        mPvwxzf.setChecked(false);
                    }
                }
                break;

            case R.id.ifview_payment_wx: //微信支付
                if (isFirstUnselectyue) {
                    if (mMoneyStatus == MONEY_ENOUGH) {
                        // isFirstUnselectyue = false;
                        mPvwxzf.setChecked(false);
                        showConfrimDialog(true, 2);
                    } else if (mMoneyStatus == MONEY_LESS) {
                        mPvalizf.setChecked(false);
                    }
                } else {
                    if (mMoneyStatus == MONEY_LESS) {
                        mPvalizf.setChecked(false);
                    } else {
                        mPvyezf.setChecked(false);
                        mPvalizf.setChecked(false);
                    }
                }

                break;
            case R.id.ifview_payment_zfb: //支付宝支付
                if (isFirstUnselectyue) {
                    if (mMoneyStatus == MONEY_ENOUGH) {
                        // isFirstUnselectyue = false;
                        mPvalizf.setChecked(false);
                        showConfrimDialog(true, 3);
                    } else if (mMoneyStatus == MONEY_LESS) {
                        mPvwxzf.setChecked(false);
                    }
                } else {
                    if (mMoneyStatus == MONEY_LESS) {
                        mPvwxzf.setChecked(false);
                    } else {
                        mPvyezf.setChecked(false);
                        mPvwxzf.setChecked(false);
                    }
                }
                break;
        }
    }

    /**
     * 取消选择余额支付的dialog
     */
    private void showConfrimDialog(final boolean isEnough, final int btn) {
        View v = View.inflate(mContext, R.layout.dialog_yuepay, null);
        TextView text_Cancle = (TextView) v.findViewById(R.id.text_yue_cancle);
        TextView text_Confirm = (TextView) v.findViewById(R.id.text_yue_confirm);
        TextView tv_content = (TextView) v.findViewById(R.id.text_content);
        if (isEnough) {
            tv_content.setText("您要放弃保宝余额支付吗？");
        } else {
            tv_content.setText("您要放弃保宝余额支付吗？");
        }
        text_Cancle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.getInstance().dismiss();
            }
        });
        text_Confirm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.getInstance().dismiss();
                isFirstUnselectyue = false;
                switch (btn) {
                    case 1:
                        mPvyezf.setChecked(false);
                        break;
                    case 2:
                        if (isEnough) {
                            mPvyezf.setChecked(false);
                        }
                        mPvwxzf.setChecked(true);
                        break;
                    case 3:
                        if (isEnough) {
                            mPvyezf.setChecked(false);
                        }
                        mPvalizf.setChecked(true);
                        break;
                }

            }
        });
        DialogUtil.getInstance().creatAlertDialog(mContext, v, 266, 171);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder().setName("PaymentActivity Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")).build();
        return new Action.Builder(Action.TYPE_VIEW).setObject(object).setActionStatus(Action.STATUS_TYPE_COMPLETED).build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    /**
     * 余额支付成功的广播
     */
    class YEpaySuccessBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            PrintLog.d(TAG, "余额支付");
            toYEpay();
        }
    }

    /**
     * 支付成功的广播
     */
    class WXpaySuccessBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            new Thread() {
                public void run() {
                    UserInfor.getInstance().setToConfirm_wx(false);
                    Message msg = mHandler.obtainMessage();
                    msg.what = SHOW_WAIT_DIALOG;
                    mHandler.sendMessage(msg);
                    try {
                        Thread.sleep(mSleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        Message msg2 = mHandler.obtainMessage();
                        msg2.what = WXPAY_SUCCESS;
                        mHandler.sendMessage(msg2);
                    }
                }


            }.start();
        }
    }

    private void sleep() {
        PrintLog.d(TAG, "PAY_STATUS::" + PAY_STATUS);
        mOnError++;  //不超过三次
        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(mSleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    Message msg = new Message();
                    msg.what = PAY_STATUS;
                    mHandler.sendMessage(msg);
                }

            }
        }.start();
    }

    /**
     * 防止重复支付
     */
    private boolean accessible() {
        boolean result;
        String courseId = mScoreIdString; //课程id
        long paymentTime = Control.getPaymentTime(courseId);
        long currentTime = System.currentTimeMillis();
        long time = currentTime - paymentTime;
        if (paymentTime == 0) { //以前没买过
            result = true;
        } else if (time > 300000) { //五分钟以后
            result = true;
        } else {
            result = false;

            DZZWTools.dismissNotBackDialog();
            DZZWTools.showToast(mContext, "您已购买该培训计划", 1);

            Tracker_Google.getInstance().addGoogleScreenName("abnormal_paid");
            Tracker_Google.getInstance().addEvent("Pay-course", "Faild-open", "已支付，开通失败");
        }
        return result;
    }

    /**
     * 如果微信或者支付宝支付成功了 就在本地保存这个状态
     */
    private void saveSuccessResult() {
        String courseId = mScoreIdString; //课程id
        long currentTime = System.currentTimeMillis();
        Control.setPaymentTime(courseId, currentTime);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterBroadcast();
        if (mIsPayFail) {
            Intent intent = new Intent(MessageConstants.PAY_FAIL);
            intent.putExtra(ReceiverType.RECEIVER_KEY, ReceiverType.PAY_SUCESS);
            mContext.sendBroadcast(intent);
        }

    }
}
